package com.kaige.asktaoplugin60.utils;

import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * 连接管理器
 * 用于管理客户端连接与服务端连接之间的映射关系
 */
@Slf4j
public class ConnectionManager {
    
    // 存储客户端Channel到服务端Channel的映射
    private static final ConcurrentMap<Channel, Channel> clientToServerMap = new ConcurrentHashMap<>();
    
    // 存储服务端Channel到客户端Channel的映射
    private static final ConcurrentMap<Channel, Channel> serverToClientMap = new ConcurrentHashMap<>();
    
    /**
     * 建立客户端与服务端连接的映射关系
     * 
     * @param clientChannel 客户端Channel
     * @param serverChannel 服务端Channel
     */
    public static void bind(Channel clientChannel, Channel serverChannel) {
        clientToServerMap.put(clientChannel, serverChannel);
        serverToClientMap.put(serverChannel, clientChannel);
        log.info("建立连接映射关系: 客户端{} <-> 服务端{}", 
                clientChannel.remoteAddress(), serverChannel.remoteAddress());
    }
    
    /**
     * 解除客户端与服务端连接的映射关系
     * 
     * @param clientChannel 客户端Channel
     */
    public static void unbind(Channel clientChannel) {
        Channel serverChannel = clientToServerMap.remove(clientChannel);
        if (serverChannel != null) {
            serverToClientMap.remove(serverChannel);
            log.info("解除连接映射关系: 客户端{} <-> 服务端{}", 
                    clientChannel.remoteAddress(), serverChannel.remoteAddress());
        }
    }
    
    /**
     * 根据客户端Channel获取对应的服务端Channel
     * 
     * @param clientChannel 客户端Channel
     * @return 对应的服务端Channel，如果不存在则返回null
     */
    public static Channel getServerChannel(Channel clientChannel) {
        return clientToServerMap.get(clientChannel);
    }
    
    /**
     * 根据服务端Channel获取对应的客户端Channel
     * 
     * @param serverChannel 服务端Channel
     * @return 对应的客户端Channel，如果不存在则返回null
     */
    public static Channel getClientChannel(Channel serverChannel) {
        return serverToClientMap.get(serverChannel);
    }
}